<template>
  <div style="display: flex; height: 100%; flex: 1;">
    <HierarchyList :pagination="pagination" :columns="columns" :load-data="loadData"
                   ref="refHiGroup" :search-form="searchItems" :create-label="'新增分组'"
                   :add-item="addGroup" />
    <EditDialog ref="refEditDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>
    <LevelSelectorDialog ref="refLevelDlg" :load="onLoadMoveGroup" :title="'移动分组'" :tag="'分组'"
                         :root-item="{id:'',name:'分组列表'}" :finish-select="onFinishMove" />

  </div>
</template>

<script setup lang="ts">

import {onMounted, reactive, ref} from "vue";
import HierarchyList from "@/widget/list/HierarchyList.vue";
import {groupSearchForms} from "@/data/PageData";
import EditDialog from "@/components/common/EditDialog.vue";
import {msgError, msgInfo, showInfo} from "@/utils/InfoUtil";
import LevelSelectorDialog from "@/widget/selector/LevelSelectorDialog.vue";
import {useCurrent} from "@/utils/UseCurrentFunc";
import {useAssetOp} from "@/utils/UseAssetOp";
import {TYPES} from "@/stores/conf";
import {useTerminal} from "@/utils/UseTerminal";
import {getStateOptions, getStateTag, getStateText, handleResult} from "@/utils/SystemUtil";
import {buildAsset} from "@/utils/DataUtil";

const props = withDefaults(defineProps<{
  entry: any,
  hasLevel?: boolean,
  product?: boolean,
  fromDetail?: boolean,
  loadGroup?: any,
  saveGroup?: any,
  deleteGroup?: any,
  moveGroup?: any,
  loadMoveGroup?: any,
  clickCurrent?: any,
}>(), {
  hasLevel: true,
});

const refHiGroup = ref();
const refEditDlg = ref();
const refLevelDlg = ref();

const currentItem = ref();
const {onTerminal} = useTerminal(props.entry.name);
const searchItems = ref(groupSearchForms({
  show: props.product,
  onChanged: onTerminal,
}));

const {updateCurrent, current} = useCurrent(props.entry.name);
const {doLoadAsset, doSaveAsset, doDeleteAsset, doMoveAsset, doLoadMoveAsset} = useAssetOp(props.entry);

const getTargetId = () => {
  return '';
}

const rules = reactive({
  name: [{required: true, message: '请输入分组名称', trigger: ['blur']}],
})

const refresh = async () => {
  await refHiGroup.value?.refresh()
}

const onSubmit = async (item: Record<string, any>, editType: string) => {
  let result;
  let assetInfo = buildAsset(item, 'GROUP', {
    comment: item.comment || '',
    classify: "GROUP_TREE",
  });

  if (props.saveGroup) {
    result = await props.saveGroup(assetInfo);
  } else {
    result = await doSaveAsset(getTargetId(), assetInfo);
  }

  if (result && result.code === 0) {
    msgInfo('保存分组信息成功!');
    await refresh();
  } else {
    msgError(result ? result.message : '保存分组信息失败！');
  }

  return result;
}

const loadData = async (params: any) => {
  let result;
  const id: string = current().id;

  if (props.fromDetail && !id) {
    return result;
  }
  if (!props.fromDetail && id) {
    return result;
  }

  const p: any = {
    parentId: id,
    ...params,
  };

  if (props.loadGroup) {
    result = await props.loadGroup(p);
  } else {
    result = await doLoadAsset(getTargetId(), TYPES.GROUP, p)
  }

  if (result && result.code === 0 && result.data) {
    handleResult(result.data, ['comment']);
    msgInfo('加载分组信息成功!');
  } else {
    msgError(result ? result.message : '加载分组信息失败！');
  }

  return result;
}

const onFinishMove = async (item: any) => {
  const p: any = {
    assetId: currentItem.value.id,
    assetType: TYPES.GROUP,
    parentId: item.id,
  };

  if (props.moveGroup) {
    await props.moveGroup(p);
  } else {
    await doMoveAsset(getTargetId(), p);
  }
}

const onLoadMoveGroup = async (params: any) => {
  let result: any;
  const p: any = {
    assetId: currentItem.value.id,
    assetType: TYPES.GROUP,
    ...params,
  };

  if (props.loadMoveGroup) {
    result = await props.loadMoveGroup(p);
  } else {
    result = await doLoadMoveAsset(getTargetId(), p);
  }

  return result;
}

const handleDeleteGroup = async (item: any) => {
  if (props.deleteGroup) {
    return await props.deleteGroup(item);
  } else {
    return await doDeleteAsset(getTargetId(), item);
  }
}

const newGroup = () => {
  return {
    state: 1,
    type: TYPES.GROUP,
  };
}

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const columns = ref([
  {
    id: 'id',
    name: '标识',
    hideCol: true,
    show: false,
    canEdit: false,
  },
  {
    id: 'parentId',
    name: '父分组',
    hideCol: true,
    type: 'tree',
    readOnly: true,
    treeKey: 'parentName',
    canEdit: false,
  },
  {
    id: 'name',
    name: '分组名称',
    show: true,
    action: (data: any, row: any) => {
      updateCurrent({type: TYPES.GROUP, ...row})
    }
  },
  {
    id: 'code',
    name: '分组标识',
    show: true,
  },
  {
    id: 'state',
    name: '状态',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => { return getStateTag(tag); },
    tagText: (tag: number) => { return getStateText(tag); },
    options: getStateOptions()
  },
  {
    id: 'comment',
    name: '描述',
    show: true,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: true,
    canEdit: false,
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    hideCol: true,
    fixed: 'right',
    canEdit: false,
    operations: [
      props.hasLevel && {
        name: '新增子分组',
        callback: (data: any, row: any, index: number) => {
          const parent = row;

          currentItem.value = newGroup();
          currentItem.value.disabled = true;
          currentItem.value.parentId = parent.id;
          currentItem.value.treeData = [
            {
              value: parent.id,
              label: parent.name,
            }
          ]
          refEditDlg.value?.editAdd('新增分组', currentItem.value);
        }
      },
      {
        name: '编辑',
        iconType: 'primary',
        callback: (data: any, row: any, index: number) => {
          currentItem.value = row;
          refEditDlg.value?.editUpdate('编辑分组', row);
        }
      },
      props.hasLevel && {
        name: '移动',
        iconType: 'primary',
        callback: (data: any, row: any, index: number) => {
          currentItem.value = row;
          refLevelDlg.value.select();
        }
      },
      {
        type: 'confirm',
        name: '删除',
        confirm: async (data: any, row: any) => {
          if (row.children && row.children.length != 0) {
            showInfo('请先删除分组子分组！');
          } else {
            const result: any = await handleDeleteGroup(row);
            if (result && result.code == 0) {
              msgInfo('删除用户分组成功！');
              await refresh();
            } else {
              msgError(result?.message || '删除用户分组失败！');
            }
          }
        },
        cancel: () => {
        }
      }
    ]
  }
]);

const addGroup = () => {
  currentItem.value = newGroup();
  currentItem.value.parentId = current().id;
  refEditDlg.value?.editAdd('新增分组', currentItem.value);
}

onMounted(() => {

})

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
